<template>
    <div class="table">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-tickets"></i>添加抽奖</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <el-form  :model="form" :rules="rules" ref="form">
                <el-form-item  v-for="(prizes,index) in form.prizes "  :key="prizes.key">
                    <el-form-item label="奖品类型"  label-width="100px" :prop="'prizes.' + index + '.type'" :rules="{required: true, message: '请选择奖品类型', trigger: 'change'}">
                        <el-select  placeholder="请选择奖品类型" v-model="prizes.type">
                            <el-option label="实物奖品"  value="1"></el-option>
                            <el-option label="优惠劵奖品" value="2"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="奖品名称" label-width="100px" :prop="'prizes.' + index + '.prizeName'" :rules="{required: true, message: '请输入奖品名称', trigger: 'blur'}">
                                <el-input type="text"  class="handle-input" clearable  v-model="prizes.prizeName"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="奖品数量" label-width="100px" :prop="'prizes.' + index + '.count'" :rules="{type:'number',required: true, message: '请输入数字类型奖品数量'}">
                                <el-input type="text" class="handle-input" clearable @input="inputChange"  v-model.number="prizes.count"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form-item>

                <el-button type="primary" class="handle-botton" @click="addPrize">添加奖品</el-button>
                <el-form-item label="赞助商" label-width="100px" prop="prizeProvider">
                    <el-input type="text" class="handle-input" clearable  v-model="form.prizeProvider"></el-input>
                </el-form-item>
                <el-row>
                    <el-col :span="4">
                        <el-form-item label="是否跳转到小程序">
                            <el-radio-group v-model="form.isForward" @change="jumpxcx">
                                <el-radio :label="1">是</el-radio>
                                <el-radio :label="0">否</el-radio>
                            </el-radio-group>
                        </el-form-item> 
                    </el-col>
                    <el-col :span="5" v-if="form.isForward == 1">
                        <el-form-item label="小程序名称"  prop="smAppName">
                            <el-input  type="text" class="handle-input" clearable v-model="form.smAppName"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5" v-if="form.isForward == 1">
                        <el-form-item label="小程序Appid" prop="smAppId">
                            <el-input type="text" class="handle-input" clearable v-model="form.smAppId"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5" v-if="form.isForward == 1">
                        <el-form-item label="跳转路径" prop="smAppUrl">
                            <el-input type="text" class="handle-input" clearable v-model="form.smAppUrl"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="奖品图片" label-width="100px" prop="activityPrizeImgUrl">
                    <el-upload
                        action="https://lottery.yhhvip.shop/yhh-lottery/home/upload/img"
                        list-type="picture-card"
                        name="file"
                        :show-file-list="true"
                        :on-preview="handlePictureCardPreview"
                        :on-change="uploadState"
                        :on-remove="handleRemove"
                        :on-success="uploadSuccess"
                        :limit=imgLimit
                        :on-exceed="uploadExceed">
                        <i class="el-icon-plus"></i>
                        </el-upload>
                        <el-dialog :visible.sync="dialogVisible" width="35%">
                            <img width="100%"  :src="form.activityPrizeImgUrl" alt="">
                    </el-dialog>
                </el-form-item>   
               
                <el-form-item label="开启倒计时" v-if="form.ruleType == 1" label-width="100px" prop="isCdown">
                    <el-radio-group v-model="form.isCdown">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                  <el-form-item label="开奖指定" label-width="100px" prop="appoint">
                    <el-radio-group @change="openApponit" v-model="form.appoint">
                            <el-radio :label="1">是</el-radio>
                            <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                    <div class="appoint" v-if="form.appoint == 1">
                        <div class="appoint-div">
                            <el-form-item v-for="(userId,index) in form.userOpenId" :key="userId.key"  :prop="'userOpenId.' + index + '.openId'" :rules="{required: true, message: '请输入用户openId', trigger: 'blur'}">
                                用户openID：<el-input v-model="userId.openId" clearable type="text" class="handle-input" placeholder="请输入内容"></el-input><span class="tips" v-if="index==0">*请在上架后再添加openID，避免中奖者在参与者名单中排在第一个</span>
                            </el-form-item>
                        </div>
                        <div class="appoint-div appoint-bottom">
                            <el-button type="primary" @click="addOpenId">添加用户openID</el-button>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="参与条件"  label-width="100px" prop="joinCondType">
                    <el-select  placeholder="请选择参与条件" @change="condType" v-model="form.joinCondType">
                    <el-option label="无条件"  value="0"></el-option>
                    <el-option label="参与密码" value="1"></el-option>
                    <el-option label="参与次数" value="2"></el-option>
                    <el-option label="参与密码与次数" disabled value="3"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="参与口令" label-width="100px" v-if="form.joinCondType == 1">
                    <el-form-item prop="">
                        <el-input type="text" class="handle-input" clearable v-model="form.joinPwd"></el-input>
                    </el-form-item>
                </el-form-item>
                <el-form-item label="参与次数" label-width="100px" v-if="form.joinCondType == 2">
                    <el-input type="text" class="handle-input" v-model="form.joinLimit"></el-input>
                </el-form-item>
                <el-form-item label="裂变抽奖"  label-width="100px" prop="sprType">
                    <el-radio-group v-model="form.sprType" @change="fission">
                        <el-radio :label="2">开启</el-radio>
                        <el-radio :label="1">不开启</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="邀请排行榜" label-width="100px" v-if="form.sprType == 1"  prop="isRank">
                    <el-radio-group v-model="form.isRank" @change="rankings">
                        <el-radio :label="1">开启</el-radio>
                        <el-radio :label="0">不开启</el-radio>
                        
                    </el-radio-group>
                </el-form-item>
                 <el-form-item label="状态" label-width="100px" prop="putStatus">
                    <el-radio-group v-model="form.putStatus" @change="status">
                        <el-radio :label="1">上架</el-radio>
                        <el-radio :label="0">下架</el-radio>
                        <el-radio :label="2">自动上架</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="自动上架时间" label-width="110px" v-if="form.putStatus == 2" prop="autoPutaway">
                    <el-date-picker v-model="form.autoPutaway"  type="datetime" format="yyyy-MM-dd H:mm" value-format="yyyy-MM-dd H:mm" :picker-options="pickerOptions"  placeholder="请选择自动上架时间" ></el-date-picker>                  
                </el-form-item>
                 <el-form-item label="开奖方式" label-width="100px">
                    <el-radio-group  @change="modeRadio" v-model="form.ruleType">
                        <el-row class="mode">
                            <el-col :span="10" class="mode-col ">
                                <el-radio :label="1" >时间开奖</el-radio>
                            </el-col>
                            <el-col :span="10" v-if="form.ruleType == 1">
                                <el-form-item prop="setLotteryTime">
                                    <el-date-picker v-model="form.setLotteryTime" type="datetime" format="yyyy-MM-dd H:mm" value-format="yyyy-MM-dd H:mm" :picker-options="pickerOptions" placeholder="请选择开奖时间" ></el-date-picker> 
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row  class="mode">
                            <el-col :span="10" class="mode-col">
                                <el-radio  :label="2" >人数开奖</el-radio>
                            </el-col>
                             <el-col :span="10" v-if="form.ruleType == 2">
                                 <el-form-item prop="setNum">
                                     <el-input type="text" class="handle-input" @input="setNumVer" clearable v-model.number="form.setNum"></el-input>
                                 </el-form-item>
                                
                            </el-col>
                        </el-row>
                        <!-- <el-radio label="线下场地免费"></el-radio> -->
                    </el-radio-group>
                </el-form-item>
                
                <el-form-item label="权重排序" label-width="100px" prop="sort">
                    <el-input type="text" v-model.number="form.sort" clearable class="handle-input"></el-input><span class="tips">*越大越靠前</span>
                </el-form-item>
                <el-form-item label="活动介绍" label-width="100px" prop="providerInformation"> 
                    <div id="editorElem"></div>
                </el-form-item>
                <el-form-item label-width="100px">
                    <el-button type="primary" @click="onSubmit('form')">立即提交</el-button>
                    <el-button>取消</el-button>
                </el-form-item>
                </el-form>
        </div>
    </div>
</template>

<script>
import { Message } from 'element-ui';
import E from 'wangeditor';
import { addLuckDraw,addOpenIdData } from '../../components/api/LuckDraw.js';
    export default {
        name: 'addLuckDraw',
        data() {
            return {
                form: {
                    prizeProvider:'',
                    joinCondType:'',
                    joinPwd:'',
                    joinLimit:'',
                    ruleType:1,
                    isForward:0,
                    sprType:1,
                    appoint:0,
                    putStatus:1,
                    smAppUrl:'',
                    smAppId:'',
                    smAppName:'',
                    setNum:'',
                    isCdown:0,
                    autoPutaway:'',
                    sort:'',
                    setLotteryTime:'',
                    prizes: [{
                        prizeName:'',
                        count:'',
                        type:'',
                        level:1
                    }],
                    userOpenId:[{
                        openId:''
                    }],
                    activityPrizeImgUrl: '',
                    providerInformation:'',
                    isRank:0
                },
                 rules:{
                    prizeProvider: [
                        { required:true, message:'请填写赞助商' , trigger: 'blur' }
                    ],
                    joinCondType: [
                        { required:true, message:'请填写参与条件' , trigger: 'change' }
                    ],
                    autoPutaway: [
                        { required: true, message: '请选择自动上架时间', trigger: 'blur'}
                    ],
                    sort: [
                        { required:true, message:'请填写权重排序'},
                        { type:'number',message:'请输入数字'}
                    ],
                    smAppUrl:[
                        {required:true,message:'请填写小程序跳转路径',trigger:'blur'}
                    ],
                    smAppId:[
                        {required:true,message:'请填写小程序Appid',trigger:'blur'}
                    ],
                    smAppName:[
                        {required:true,message:'请填写小程序名称',trigger:'blur'}
                    ],
                    openId:[
                        {required:true,message:'请输入openId',trigger:'blur'}
                    ],
                    putStatus:[
                        {required:true,message:'请选择状态',trigger: 'change'}
                    ],
                    ruleType:[
                        {required:true,message:'请选择开奖方式',trigger:'change'}
                    ],
                    setLotteryTime:[
                        {required:true, message:'请选择开奖时间' , trigger: 'blur'}
                    ],
                    setNum:[
                        { required:true,message:'请选择开奖人数'},
                        { type: 'number', message: '请输入数字值'}
                    ],
                    providerInformation:[
                        {required:true,message:'请填写活动介绍',trigger:'change'}
                    ],
                    // activityPrizeImgUrl:[
                    //     {required:true,message:'请上传奖品图片',trigger:'change'}
                    // ]

                },
                upload:true,
                imgLimit:1,
                dialogVisible: false,
                index:1,
                level:1,
                prizesNumber:0,
                pickerOptions:{
                    disabledDate(time) {
                        return time.getTime() < Date.now() - 8.64e7;
                    }
                }
            }
        },
        components:{
            
        },   
        watch:{
            form:{
                handler:function(nowVal,oldVal){
                    console.log(nowVal);
                    console.log(oldVal);
                }
            }
        },   
         mounted() {

            //活动介绍富文本
            this.editor();
           
        },
        
        methods: {
            
            //奖品数据改变时触发
            inputChange(value){
                console.log(value);
                console.log(this.form.prizes.count);
                let prizes = this.form.prizes;
                let userOpenId = this.form.userOpenId;

                let count = 0;
                for(let i=0,len = prizes.length;i<len;i++){
                    count += prizes[i].count;
                }               
                
                if(userOpenId.length < count){
                    for(let j=userOpenId.length;j<count;j++){
                        this.form.userOpenId.push({openId:''});
                    }
                }else{
                    this.form.userOpenId.splice(count-1,(userOpenId.length-count));
                }
            },

            //人数开奖只能输入数字
            setNumVer(value){
                // this.form.setNum = 
                // this.form.setNum =  this.form.setNum.replace(/\D/g,'');
            },
            
            addPrize() {
                let level = this.level = this.level+1;
                this.form.prizes.push({
                   prizeName:'',
                   count:'',
                   type:'',
                   level:level,
                });
            },

            //重置表单
            resetForm(formName){
                this.$refs[formName].resetFields();
            },

            //图片上传
            uploadState(file,fileList){
                console.log('文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用');
                console.log(file.response);
              
            },
           
            handleRemove(file,fileList){
                console.log('文件列表移除文件时的钩子');
                console.log(file);
                console.log(fileList);
            },
            handlePictureCardPreview(file,fileList){
                console.log('点击文件列表中已上传的文件时的钩子');
                let imgUrl = file.response.data.domain+file.response.data.url;
                this.form.activityPrizeImgUrl = file.response.data.domain+file.response.data.url;
                this.dialogVisible = true;
            },

            

            //上传图片的限制
            uploadExceed(file,fileList){
                if(file){
                    Message({
                        message:'只能上传1张图片',
                        type:'warning'
                    });
                    // this.upload = false;
                    // console.log('吵多了');
                }
            },

            //奖品图片上传成功时的函数
            uploadSuccess(file,fileLIst){
                console.log('图片上传成功时的函数');
                console.log(file);
                if(file.status == 200){
                    this.form.activityPrizeImgUrl = file.data.domain+file.data.url;
                    Message({
                        message:'上传成功',
                        type:'success'
                    });

                }
                
            },

            //是否跳转小程序
            jumpxcx(value){
                this.form.isForward = value;
                if(value == 0){
                    this.form.smAppName = '';
                    this.form.smAppId = '';
                    this.form.smAppUrl = '';
                } 
            },

            //开奖方式单选
            modeRadio(value){
                this.mode = value;
                this.form.setLotteryTime = '';
                this.form.setNum = '';
            },

            //是否开启指定
            openApponit(value){
                this.appoint = value;
                console.log(value);
                console.log(this.form.prizes);
                if(value == 0){
                    let openid = this.form.userOpenId;
                    for(let i=0,len = openid.length;i<len;i++){
                        openid[i].openId = ''
                    }
                }
            },

            //添加用户openid
            addOpenId(){

                let prizesData = this.form.prizes;
                let sum = 0;
                let userOpenIdSum = this.form.userOpenId.length;

                for(let i=0,len = prizesData.length;i<len;i++){
                    sum += Number(prizesData[i].count);
                }

                console.log(userOpenIdSum);
               
                if(userOpenIdSum < sum){
                    this.form.userOpenId.push({
                        openId: '',
                    });
                }else if(userOpenIdSum == 1){
                     Message({
                        message:'请先填写奖品数量',
                        type:'warning'
                    });
                }else{
                    Message({
                        message:'只能添加'+sum+'个openId',
                        type:'warning'
                    });
                }
                
            },
            
            //参与条件
            condType(value){
                this.form.joinCondType = value;
                this.form.joinPwd = '';
                this.form.joinLimit = '';
            },

            //开启裂变
            fission(value){
                console.log(value);
                console.log(this.form.isRank);
                if(value == 2){
                    this.form.isRank = 0;
                }
            },
            rankings(value){
                console.log(value);
                if(value == 1){
                    this.form.sprType = 1;
                }  
            },

            //状态
            status(value){
                this.putStatus = value;
            },

            //活动介绍富文本
            editor(){
                let editor = new E('#editorElem')
                editor.customConfig.showLinkImg = false;
                editor.customConfig.uploadImgServer = 'https://lottery.yhhvip.shop/yhh-lottery/home/upload/img';  // 上传图片到服务器
                editor.customConfig.withCredentials = true;
                editor.customConfig.uploadImgParamsWithUrl = true;
                editor.customConfig.uploadFileName = 'file';

                editor.customConfig.uploadImgHooks = {

                    // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
                    // （但是，服务器端返回的必须是一个 JSON 格式字符串！！！否则会报错）
                    customInsert: function (insertImg, result, editor) {
                        console.log(result);
                        if(result.status == 200){
                            let imgUrl = result.data;
                            insertImg(imgUrl.domain+imgUrl.url)
                        }
                    }
                };
                
                //用户操作（鼠标点击、键盘打字等）导致的内容变化之后，会自动触发此函数并获取富文本中的所有内容
                editor.customConfig.onchange = (html) => {
                    this.form.providerInformation = html
                } 
                editor.customConfig.zIndex = 1;    //防止富文本编辑器被别的内容所覆盖     
                editor.create();
            },

            //提交表单
            onSubmit(formName){
                
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        console.log(JSON.stringify(this.form));
                        let sysUser = JSON.parse(localStorage.getItem('sysUser'));
                        let router = this.$router;

                        let luckDrawData = {
                          prizeProvider:this.form.prizeProvider,
                          joinCondType:this.form.joinCondType,
                          joinPwd:this.form.joinPwd,
                          joinLimit:this.form.joinLimit,
                          ruleType:this.form.ruleType,
                          isForward:this.form.isForward,
                          sprType:this.form.sprType,
                          appoint:this.form.appoint,
                          putStatus:this.form.putStatus,
                          smAppUrl:this.form.smAppUrl,
                          smAppId:this.form.smAppId,
                          smAppName:this.form.smAppName,
                          setNum:this.form.setNum,
                          isCdown:this.form.isCdown,
                          autoPutaway:this.form.autoPutaway,
                          sort:this.form.sort,
                          setLotteryTime:this.form.setLotteryTime,
                          prizes:this.form.prizes,
                          createById:sysUser.id,
                          createByName:sysUser.username,
                          activityPrizeImgUrl:this.form.activityPrizeImgUrl,
                          type:1,
                          providerInformation:this.form.providerInformation,
                          isRank:this.form.isRank
                        }; 

                        console.log(luckDrawData);
                        // console.log(JSON.stringify(this.form.userOpenId));
                        addLuckDraw(luckDrawData).then((res)=>{
                            if(res.status == 200){
                                let id = this.form.userOpenId;
                                
                                let openIdObj = [];
                                for(let i=0,len = id.length;i<len;i++){
                                    if(id[i].openId != ''){
                                        let obj = {
                                            openId:id[i].openId,
                                            activityId:res.data
                                        };
                                        openIdObj.push(obj);
                                    }
                                    
                                }
                                if(openIdObj.length != 0){
                                    addOpenIdData(openIdObj).then((res)=>{
                                        console.log(res);
                                        if(res.status == 200){
                                           Message({
                                                message:'添加成功',
                                                type:'success',
                                                duration:2000,
                                                onClose:function(){
                                                    router.push('/LuckDrawList');
                                                }
                                            });
                                        }
                                        
                                    }).catch((err)=>{
                                        console.log(err);
                                    });
                                }else{
                                    Message({
                                        message:'添加成功',
                                        type:'success',
                                        duration:2000,
                                        onClose:function(){
                                             router.push('/LuckDrawList');
                                        }
                                    });

                                }
                                
                            }else{
                                console.log(res);
                                // Message({
                                //     message:'',
                                //     type:'success',

                                // });
                            }
                        }).catch((err)=>{
                            console.log(err);
                             Message.error(err.msg);
                        });

                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            }
        }
    }

</script>

<style scoped>
    .add-user{
        float:right;
    }
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 130px;
    }

    .handle-input {
        width: 213px;
        display: inline-block;
    }
    .del-dialog-cnt{
        font-size: 16px;
        text-align: center
    }
    .handle-botton{
        margin: 0 0 20px 100px;
    }
    .mode{
        height:40px;margin-top:20px;
    }
    .mode-col{
        padding-top:9px;
    }
    .appoint{
        background:rgb(251, 249, 251);
        width:100%;
    }
    .appoint-div{
        padding:20px 0 0 40px;
    }
    .appoint-bottom{
        padding-bottom:20px;
    }
    .tips{
        color:red;
        margin-left:15px;
    }
    .aaa{
        z-index: 1;
    }

</style>
